package com.lishe.lishe.lishe.module.giftnote.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.TextView;

import com.lishe.lishe.R;
import com.lishe.lishe.asynchttp.LSWebHelper;
import com.lishe.lishe.lishe.common.Globals;
import com.lishe.lishe.lishe.module.mall.base.SearchBaseActivity;
import com.lishe.lishe.lishe.module.mall.view.SearchBarView;
import com.lishe.lishe.lishe.module.me.activity.AboutActivity;

/**
 * Created by zhcase on 2017/9/12.
 */

public class GiftNoteActivity extends SearchBaseActivity {

    private final static String TAG = GiftNoteActivity.class.getSimpleName();

    private EditText mSearchView;

    private View mall_search_panel, mall_index_panel, search_container;

    private SearchBarView search_bar;

    private WebView myWebView;
    private  String url;
    private  WebSettings webSettings;
    public final static int FILECHOOSER_RESULTCODE = 1001;
    public final static int FILECHOOSER_RESULTCODE_FOR_ANDROID_5 = 1002;
    private ValueCallback<Uri> mUploadMessage;
    private ValueCallback<Uri[]> mUploadCallbackAboveL;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gift_note);
        url = LSWebHelper.BASE_URL + "Home/Giftrecord/index?token=" + Globals.getToken();
        initView();
        mSearchView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.e("开始", "搜索");
            }
        });

        mSearchView.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                Log.e(TAG, "onFocusChange:" + b);
                if (b) {
                    search_bar.setVisibility(View.VISIBLE);
                    mSearchView.clearFocus();
                    mall_search_panel.setVisibility(View.VISIBLE);
                    mall_index_panel.setVisibility(View.INVISIBLE);
                    search_bar.requestEditFocus();
                    search_bar.setOnButton(new Runnable() {
                        @Override
                        public void run() {
                            mall_search_panel.setVisibility(View.INVISIBLE);
                            mall_index_panel.setVisibility(View.VISIBLE);
                            ((View) mSearchView.getParent()).setFocusable(true);
                            ((View) mSearchView.getParent()).setFocusableInTouchMode(true);
                            ((View) mSearchView.getParent()).requestFocus();
                            Log.e("开始1", "搜索");
                        }
                    });
                } else {
                    Log.e("开始2", "搜索");
                }
            }
        });

        //这是覆盖在最上面面的搜索
        search_bar.getEditTextSearch().setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {

                if(actionId == EditorInfo.IME_ACTION_SEARCH)
                {
                    Log.e(TAG,"mSearchView"+"IME_ACTION_SEARCH");

                    // 先隐藏键盘
                    ((InputMethodManager) mSearchView.getContext()
                            .getSystemService(Context.INPUT_METHOD_SERVICE))
                            .hideSoftInputFromWindow(GiftNoteActivity.this
                                            .getCurrentFocus().getWindowToken(),
                                    InputMethodManager.HIDE_NOT_ALWAYS);
                    // 搜索中。。。
                    String keywords=search_bar.getEditTextSearch().getText().toString();
                    if(TextUtils.isEmpty(keywords)){
                        return false;
                    }
                    mall_search_panel.setVisibility(View.GONE);
                    mall_index_panel.setVisibility(View.VISIBLE);
                    mSearchView.clearFocus();
//                    myWebView.loadUrl(Globals.URL_GIFT_RECOR_SERCH+"?keywords="+keywords);
                    AboutActivity.jump(GiftNoteActivity.this,"",Globals.URL_GIFT_RECOR_SERCH+"?keywords="+keywords);
                    return true;
                }

                return false;
            }
        });

    }



    public static void jump(Activity activity) {
        Intent intent = new Intent(activity, GiftNoteActivity.class);
        activity.startActivity(intent);
    }


    private void initView() {

        mSearchView = (EditText) findViewById(R.id.search_view);

        mall_search_panel = (View) findViewById(R.id.mall_search_panel);

        mall_index_panel = (View) findViewById(R.id.mall_index_panel);

        search_container = (View) findViewById(R.id.search_container);

        search_bar = (SearchBarView) findViewById(R.id.search_bar);

        TextView search_view_hint = (TextView) findViewById(R.id.search_view_hint);
        search_view_hint.setText("搜索礼物记");
        myWebView = findViewById(R.id.webView);
        webSettings = myWebView.getSettings();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            webSettings.setLoadsImagesAutomatically(true);
        } else {
            webSettings.setLoadsImagesAutomatically(false);
        }

        //如果访问的页面中要与Javascript交互，则webview必须设置支持Javascript
        webSettings.setJavaScriptEnabled(true);

//支持插件
//        webSettings.setPluginsEnabled(true);

//设置自适应屏幕，两者合用
        webSettings.setUseWideViewPort(true); //将图片调整到适合webview的大小
        webSettings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小

//缩放操作
        webSettings.setSupportZoom(true); //支持缩放，默认为true。是下面那个的前提。
        webSettings.setBuiltInZoomControls(true); //设置内置的缩放控件。若为false，则该WebView不可缩放
        webSettings.setDisplayZoomControls(true); //隐藏原生的缩放控件

//其他细节操作
        webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); //关闭webview中缓存
        webSettings.setAllowFileAccess(true); //设置可以访问文件
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口
        webSettings.setLoadsImagesAutomatically(true); //支持自动加载图片
        webSettings.setDefaultTextEncodingName("utf-8");//设置编码格式
        myWebView.clearCache(true);
        myWebView.setWebViewClient(new MyWebViewClient());
        myWebView.setWebChromeClient(new MyWebChromeClient());
        myWebView.loadUrl(url);
    }

    private class MyWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            Log.e("url", url);
            return true;
        }

        @Override
        public void onReceivedError(WebView view, int errorCode,
                                    String description, String failingUrl) {
            // TODO Auto-generated method stub
            super.onReceivedError(view, errorCode, description, failingUrl);

        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            myWebView.setVisibility(View.VISIBLE);
        }
    }

    boolean isOnPause = false;

    @Override
    public void onPause() {
        myWebView.onPause();
        super.onPause();

    }

    @Override
    public void onResume() {
        // TODO Auto-generated method stub
        myWebView.onResume();
        super.onResume();

    }

    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        myWebView.destroy();
        super.onDestroy();
    }

    private class MyWebChromeClient<FileChooserParams> extends WebChromeClient {

        // For Android < 3.0
        public void openFileChooser(ValueCallback<Uri> uploadMsg) {
            openFileChooserImpl(uploadMsg);
        }

        // For Android 3.0+ 文件选择
        public void openFileChooser(ValueCallback uploadMsg, String acceptType) {
            openFileChooserImpl(uploadMsg);
        }

        // For Android > 4.1.1
        public void openFileChooser(ValueCallback<Uri> uploadMsg,
                                    String acceptType, String capture) {
            openFileChooserImpl(uploadMsg);
        }

        // For Android > 4.4 为了支持安卓5.0和6.0等高版本系统
        public boolean onShowFileChooser(WebView webView,
                                         ValueCallback<Uri[]> filePathCallback,
                                         FileChooserParams fileChooserParams) {
            openFileChooserImplForAndroid5(filePathCallback);
            return true;
        }
    }

    private void openFileChooserImpl(ValueCallback<Uri> uploadMsg) {
        mUploadMessage = uploadMsg;
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.setType("image/*");
        startActivityForResult(Intent.createChooser(i, "File Chooser"),
                FILECHOOSER_RESULTCODE);
    }

    private void openFileChooserImplForAndroid5(ValueCallback<Uri[]> uploadMsg) {
        mUploadCallbackAboveL = uploadMsg;
        Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
        contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
        contentSelectionIntent.setType("image/*");

        Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
        chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
        chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");
        startActivityForResult(chooserIntent,
                FILECHOOSER_RESULTCODE_FOR_ANDROID_5);
    }


    @Override
    public void onBackPressed() {
        if (myWebView.canGoBack()) {
            myWebView.goBack();
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Uri result = (data == null || resultCode != RESULT_OK) ? null : data
                .getData();
        if (requestCode == FILECHOOSER_RESULTCODE) {
            if (null == mUploadMessage)
                return;
            mUploadMessage.onReceiveValue(result);
            mUploadMessage = null;

        } else if (requestCode == FILECHOOSER_RESULTCODE_FOR_ANDROID_5) {
            if (null == mUploadCallbackAboveL)
                return;
            if (result != null) {
                mUploadCallbackAboveL.onReceiveValue(new Uri[]{result});
            } else {
                mUploadCallbackAboveL.onReceiveValue(new Uri[]{});
            }
            mUploadCallbackAboveL = null;
            // onActivityResultAboveL(requestCode, resultCode, data);
        }
    }
}
